package com.lsyw.intergrate.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lsyw.intergrate.common.Result;
import com.lsyw.intergrate.entity.Device;
import com.lsyw.intergrate.entity.Massif;
import com.lsyw.intergrate.entity.Monitoring;
import com.lsyw.intergrate.entity.common.PageInfo;
import com.lsyw.intergrate.service.DeviceService;
import com.lsyw.intergrate.service.MassifService;
import com.lsyw.intergrate.service.MonitoringService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 设备信息表 前端控制器
 * </p>
 *
 * @author 刘磊
 * @since 2023-11-29
 */
@Api(tags = "设备信息表")
@RestController
@RequestMapping("/device")
public class DeviceController {


    @Autowired
    private DeviceService deviceService;
    @Autowired
    private MassifService massifService;
    @Autowired
    private MonitoringService monitoringService;
    /**
     * 通过id查询
     */
    @GetMapping("/get-by-id")
    @ApiOperation(value = "通过id查询", notes = "通过id查询", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String")
    })
    public Result getById(String id) {
        Device device = deviceService.getById(id);

        String massifId = device.getMassifId();
        Massif massif = this.massifService.getById(massifId);
        String monitoringId = device.getMonitoringId();
        Monitoring monitoring = this.monitoringService.getById(monitoringId);

        Map<String, Object> map = BeanUtil.beanToMap(device);
        map.put("massifName",massif.getName());
        map.put("monitoringName",monitoring.getName());

        return Result.successResult(map);
    }

    /**
     * 新增
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增", notes = "新增", httpMethod = "POST")
    public Result save(@RequestBody Device device) {
        Device byId = this.deviceService.getByCode(device.getCode());
        if (byId !=null){
            return Result.errorResult(null,"编号不唯一");
        }
        deviceService.save(device);
        return Result.successResult(null);
    }


    /**
     * 通过id删除
     */
    @GetMapping("/delete-by-id")
    @ApiOperation(value = "通过id删除", notes = "通过id删除", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String")
    })
    public Result delete(String id) {
        Device byId = this.deviceService.getById(Long.parseLong(id));
        byId.setDelFlag(1);
        this.deviceService.updateById(byId);
        return Result.successResult(null);
    }


    /**
     * 二维地图打点
     */
    @GetMapping("/update-xy")
    @ApiOperation(value = "二维地图打点", notes = "二维地图打点", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "x", value = "x", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "y", value = "y", required = true, paramType = "query", dataType = "Integer")
    })
    public Result updateById( String  x ,String  y,String id) {
        Device device = this.deviceService.getById(id);
        device.setXId(x);
        device.setYId(y);
        this.deviceService.updateById(device);
        return Result.successResult(null);
    }

    /**
     * 修改状态
     */
    @GetMapping("/update-status")
    @ApiOperation(value = "通过id删除", notes = "通过id删除", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "status", value = "status", required = true, paramType = "query", dataType = "Integer")
    })
    public Result updateById( String  id ,Integer status) {
        Device device = this.deviceService.getById(id);
        device.setStatus(status);
        this.deviceService.updateById(device);
        return Result.successResult(null);
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperation(value = "修改", notes = "修改", httpMethod = "POST")
    public Result updateById(@RequestBody Device device) {
        deviceService.updateById(device);
        return Result.successResult(null);
    }


    /**
     * 查询列表
     */
    @PostMapping("/list")
    @ApiOperation(value = "查询列表", notes = "查询列表", httpMethod = "POST")
    public Result list(@RequestBody DeviceReqVo device) {
        final LambdaQueryWrapper<Device> lambda = new QueryWrapper<Device>().lambda();
        this.buildCondition(lambda, device);
        return Result.successResult(deviceService.list(lambda));
    }

    /**
     * 根据设备类型获取设备列表
     */
    @GetMapping("/listByType")
    @ApiOperation(value = "根据设备类型获取设备列表", notes = "根据设备类型获取设备列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "type", required = true, paramType = "query", dataType = "String")
    })
    public Result listByType(String type) {
        LambdaQueryWrapper<Device> lambda = new QueryWrapper<Device>().lambda();
       // this.buildCondition(lambda, device);
        lambda.orderBy(true, false, Device::getId);
        lambda.eq(Device::getDelFlag,0);
        lambda.eq(Device::getType,type);
        return Result.successResult(deviceService.list(lambda));
    }
    /**
     * 转运记录
     */
    @GetMapping("/getDevice")
    @ApiOperation(value = "获取工地下设备", notes = "获取工地下设备", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "massifId", value = "地块id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "types", value = "设备类型，多个以,隔开", required = true, paramType = "query", dataType = "String")
    })
    public Result getDevice(String massifId, String types) {

        final LambdaQueryWrapper<Device> lambda = new QueryWrapper<Device>().lambda();
        lambda.eq(Device::getDelFlag, 0);
        lambda.eq(Device::getMassifId, massifId);
        List<String> list = Arrays.asList(types.split(","));
        lambda.in(Device::getType, list);
        return Result.successResult(deviceService.list(lambda));
    }

    /**
     * 分页查询
     */
    @PostMapping("/page")
    @ApiOperation(value = "分页查询", notes = "分页查询", httpMethod = "POST")
    public Result page(@RequestBody PageInfo pageInfo) {
        Page<Device> page = new Page<>();
        page.setSize(pageInfo.getPageSize());
        page.setCurrent(pageInfo.getPageNum());
        final LambdaQueryWrapper<Device> lambda = new QueryWrapper<Device>().lambda();
        lambda.eq(Device::getDelFlag,0);
        Map<String, Object> condition = pageInfo.getCondition();
        if (condition.get("name") != null && !StringUtils.isEmpty(condition.get("name").toString())) {
            lambda.like(Device::getName, condition.get("name"));
        }
        if (condition.get("massifId") != null && !StringUtils.isEmpty(condition.get("massifId").toString())) {
            lambda.like(Device::getMassifId, condition.get("massifId"));
        }
        if (condition.get("monitoringId") != null && !StringUtils.isEmpty(condition.get("monitoringId").toString())) {
            lambda.like(Device::getMonitoringId, condition.get("monitoringId"));
        }
        if (condition.get("type") != null && !StringUtils.isEmpty(condition.get("type").toString())) {
            lambda.eq(Device::getType, condition.get("type"));
        }
        Page<Device> page1 = this.deviceService.page(page, lambda);
        List<Device> records = page1.getRecords();
        for (int i = 0; i <records.size() ; i++) {
            Device device = records.get(i);
            String massifId = device.getMassifId();
            String monitoringId = device.getMonitoringId();
            Massif massif = this.massifService.getById(massifId);
            Monitoring monitoring = this.monitoringService.getById(monitoringId);
            if (massif!=null){
                records.get(i).setMassifName(massif.getName());
            }
            if (monitoring!=null){
                records.get(i).setMonitoringName(monitoring.getName());
            }
        }
        page1.setRecords(records);

        return Result.successResult(page1);
    }


    /**
     * 构造查询条件
     *
     * @param lambda
     * @param param
     */
    private void buildCondition(LambdaQueryWrapper<Device> lambda, DeviceReqVo param) {
        if (!StringUtils.isEmpty(param.getId())) {
            lambda.eq(Device::getId, param.getId());
        }
        if (!StringUtils.isEmpty(param.getName())) {
            lambda.eq(Device::getName, param.getName());
        }
        if (!StringUtils.isEmpty(param.getType())) {
            lambda.eq(Device::getType, param.getType());
        }
        if (!StringUtils.isEmpty(param.getCode())) {
            lambda.eq(Device::getCode, param.getCode());
        }
        if (!StringUtils.isEmpty(param.getStatus())) {
            lambda.eq(Device::getStatus, param.getStatus());
        }
        if (!StringUtils.isEmpty(param.getIconPath())) {
            lambda.eq(Device::getIconPath, param.getIconPath());
        }
        if (!StringUtils.isEmpty(param.getGmtCreateUser())) {
            lambda.eq(Device::getGmtCreateUser, param.getGmtCreateUser());
        }
        if (!CollectionUtils.isEmpty(param.getGmtCreateList())) {
            lambda.ge(Device::getGmtCreate, param.getGmtCreateList().get(0));
            lambda.le(Device::getGmtCreate, param.getGmtCreateList().get(1));
        }
        if (!StringUtils.isEmpty(param.getGmtModifiedUser())) {
            lambda.eq(Device::getGmtModifiedUser, param.getGmtModifiedUser());
        }
        if (!CollectionUtils.isEmpty(param.getGmtModifiedList())) {
            lambda.ge(Device::getGmtModified, param.getGmtModifiedList().get(0));
            lambda.le(Device::getGmtModified, param.getGmtModifiedList().get(1));
        }
        if (!StringUtils.isEmpty(param.getDelFlag())) {
            lambda.eq(Device::getDelFlag, param.getDelFlag());
        }
        if (!StringUtils.isEmpty(param.getIp())) {
            lambda.eq(Device::getIp, param.getIp());
        }
        if (!StringUtils.isEmpty(param.getMonitoringId())) {
            lambda.eq(Device::getMonitoringId, param.getMonitoringId());
        }
        if (!StringUtils.isEmpty(param.getMassifId())) {
            lambda.eq(Device::getMassifId, param.getMassifId());
        }
        lambda.orderBy(true, false, Device::getId);
    }


    /**
     * 请求model
     */
    @Data
    @AllArgsConstructor
    private static class DeviceReqVo extends Device {
        private List<String> gmtCreateList; // 创建时间起止
        private List<String> gmtModifiedList; // 更新时间起止
    }


}
